package com.vip.database.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.vip.database.constant.MPConst.MP;
import com.vip.oauth2resource.util.CustomUserDetail;
import com.vip.oauth2resource.util.UserHelper;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充字段设置
 *
 * @author wgb
 * @date 2020/3/28 10:26
 */
@Component
public class MyBatisPlusMetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter(MP.PRO_CREATE_BY)) {
            CustomUserDetail user = UserHelper.getUser();
            String createBy = user.getUsername() + "|" + user.getName();
            this.setFieldValByName(MP.PRO_CREATE_BY, createBy, metaObject);
            this.setFieldValByName(MP.PRO_UPDATE_BY, createBy, metaObject);
            this.setFieldValByName(MP.PRO_CREATE_TIME, LocalDateTime.now(), metaObject);
            this.setFieldValByName(MP.PRO_UPDATE_TIME, LocalDateTime.now(), metaObject);
            this.setFieldValByName(MP.PRO_DELETE_STATUS, false, metaObject);
        }
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter(MP.PRO_UPDATE_BY)) {
            CustomUserDetail user = UserHelper.getUser();
            this.setFieldValByName(MP.PRO_UPDATE_BY, user.getUsername() + "|" + user.getName(), metaObject);
            this.setFieldValByName(MP.PRO_UPDATE_TIME, LocalDateTime.now(), metaObject);
        }
    }

}
